package com.jinly.ryder.deploy.web;

import com.jinly.ryder.account.web.utils.AuthUtil;
import com.jinly.ryder.common.auth.LoginContent;
import com.jinly.ryder.common.auth.model.AuthRole;
import com.jinly.ryder.common.auth.model.AuthType;
import com.jinly.ryder.common.utils.FileUtil;
import com.jinly.ryder.deploy.service.DeployConfigFileService;
import com.jinly.ryder.deploy.service.model.ConfigFileType;
import com.jinly.ryder.deploy.service.model.DeployConfigFile;
import com.jinly.ryder.deploy.web.mapping.DeployConfigFileVOMapping;
import com.jinly.ryder.deploy.web.vo.DeployConfigFileVO;
import com.jinly.ryder.manage.service.DeployGroupService;
import com.jinly.ryder.manage.service.model.DeployGroup;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("deployConfigFile")
@RequiredArgsConstructor
public class DeployConfigFileController {

    private final DeployGroupService deployGroupService;
    private final DeployConfigFileService deployConfigFileService;
    private final DeployConfigFileVOMapping deployConfigFileVOMapping;

    private String uploadTempDir = System.getProperty("java.io.tmpdir") + "/upload";

    @PostMapping("save")
    public void save(@RequestBody DeployConfigFileVO deployConfigFileVO) {
        DeployGroup deployGroup = deployGroupService.get(deployConfigFileVO.getDeployGroupId());
        Assert.notNull(deployGroup, "部署组不存在");
        AuthUtil.check(AuthType.APP, deployGroup.getAppName(), AuthRole.DEVELOPER);
        DeployConfigFile deployConfigFile = deployConfigFileVOMapping.toModel(deployConfigFileVO);
        if (deployConfigFileVO.getFileType() == ConfigFileType.BINARY) {
            File uploadFile = new File(uploadTempDir + deployConfigFileVO.getUploadFile());
            if (!uploadFile.exists()) {
                throw new RuntimeException("文件不存在");
            }
            deployConfigFile.setFileContent(FileUtil.getContent(uploadFile.getAbsolutePath()));
        } else {
            deployConfigFile.setFileContent(deployConfigFileVO.getTextContent().getBytes());
        }
        deployConfigFile.setOperator(LoginContent.getUserId());
        deployConfigFileService.saveConfigFile(deployConfigFile);
    }


    @GetMapping("list")
    public List<DeployConfigFileVO> queryList(Integer deployGroupId) {
        DeployGroup deployGroup = deployGroupService.get(deployGroupId);
        Assert.notNull(deployGroup, "部署组不存在");
        AuthUtil.check(AuthType.APP, deployGroup.getAppName(), AuthRole.DEVELOPER);
        return deployConfigFileVOMapping.toVoList(deployConfigFileService.queryConfigFile(deployGroupId, false));
    }

    @GetMapping("/{fileId}")
    public DeployConfigFileVO getConfigFile(@PathVariable Integer fileId) {
        DeployConfigFile deployConfigFile = deployConfigFileService.getConfigFile(fileId);
        Assert.notNull(deployConfigFile, "文件不存在");
        DeployGroup deployGroup = deployGroupService.get(deployConfigFile.getDeployGroupId());
        Assert.notNull(deployGroup, "部署组不存在");
        AuthUtil.check(AuthType.APP, deployGroup.getAppName(), AuthRole.DEVELOPER);
        DeployConfigFileVO deployConfigFileVO = deployConfigFileVOMapping.toVo(deployConfigFile);
        if (deployConfigFile.getFileType() == ConfigFileType.TEXT) {
            deployConfigFileVO.setTextContent(new String(deployConfigFile.getFileContent()));
        }
        return deployConfigFileVO;
    }

    @DeleteMapping("/{fileId}")
    public void deleteConfigFile(@PathVariable Integer fileId) {
        DeployConfigFile deployConfigFile = deployConfigFileService.getConfigFile(fileId);
        if (deployConfigFile == null) return;
        DeployGroup deployGroup = deployGroupService.get(deployConfigFile.getDeployGroupId());
        AuthUtil.check(AuthType.APP, deployGroup.getAppName(), AuthRole.DEVELOPER);

        deployConfigFileService.deleteConfigFile(fileId);
    }

    @GetMapping("download/{fileId}")
    public void download(@PathVariable Integer fileId, HttpServletResponse response) {
        DeployConfigFile deployConfigFile = deployConfigFileService.getConfigFile(fileId);
        Assert.notNull(deployConfigFile, "文件不存在");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment;filename=" + deployConfigFile.getFileName());
            outputStream.write(deployConfigFile.getFileContent());
            outputStream.flush();
        } catch (Exception e) {
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException ioException) {
            }
        }
    }

    @PostMapping("/upload")
    @ResponseBody
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
        String fileName = "/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "/" + file.getOriginalFilename();
        File dest = new File(uploadTempDir + fileName);
        try {
            if (!dest.getAbsoluteFile().exists()) {
                dest.getAbsoluteFile().mkdirs();
            }
            file.transferTo(dest);
        } catch (IOException e) {
        }
        log.info("{}:{}", dest, dest.exists());
        return ResponseEntity.ok(fileName);
    }

}
